import { memo, useCallback, useEffect, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Button, Cascader, Checkbox, Form, Input, Modal } from 'antd';
import { resAddAddress, resChangeAddress, resCity } from '@/services/address';
import { useRequest } from 'ahooks';
import { formatPhone } from '@/utils/format';

export const validateMessage = { required: '此字段是必须的' };

interface Option {
  id: number;
  value: string | number;
  label: string;
  children?: Option[];
  isLeaf?: boolean;
  loading?: boolean;
}

const formatOption = (index: number, options: Option[]): Option[] => {
  if (index <= 0) {
    return options;
  }
  options[index - 1]?.children?.forEach((value, i) => {
    if (value.value === options[index].value) {
      const children = options[index - 1].children || [];
      children[i] = options[index];
      options[index - 1].children = children;
    }
  });
  return formatOption(index - 1, options);
};

const formatCityToOption = (cities: API.CityStruct[]) => {
  return cities.map((value) => {
    return {
      id: value.id,
      value: value.name,
      label: value.name,
      isLeaf: value.type === 3,
    };
  });
};

export const labelCol = { span: 6 };
export const wrapperCol = { span: 18 };

const AddressFormModal: FC<
  PropsWithChildren<{
    defaultValue?: API.AddressStruct;
    onFinish?: (value: any) => void;
    isModalOpen?: boolean;
    onCancel?: () => void;
    onOk?: () => void;
  }>
> = ({ defaultValue, isModalOpen, onFinish, onOk, onCancel }) => {
  const { data } = useRequest(resCity);

  const [options, setOptions] = useState<Option[]>();

  useEffect(() => {
    if (data) setOptions(formatCityToOption(data));
  }, [data]);

  const loadData = (selectedOptions: Option[]) => {
    const option = selectedOptions[selectedOptions.length - 1];
    resCity({
      pid: Number(option.id),
    }).then((childrenData) => {
      option.children = formatCityToOption(childrenData);
      formatOption(selectedOptions.length - 1, selectedOptions);
      const result = selectedOptions[0];
      if (options) {
        options.forEach((value, index) => {
          if (value.value === result.value) {
            options[index] = result;
          }
        });
        setOptions([...options]);
      }
    });
  };
  return (
    <Modal
      open={isModalOpen}
      onOk={onOk}
      onCancel={onCancel}
      title={defaultValue ? '修改地址' : '添加地址'}
      cancelText={'取消'}
      okText={'确认'}
      width={800}
      destroyOnClose
      footer={null}
    >
      <div className={' my-10 mx-24'}>
        <Form
          preserve={false}
          initialValues={defaultValue}
          onFinish={onFinish}
          validateMessages={validateMessage}
          labelCol={labelCol}
          wrapperCol={wrapperCol}
        >
          <Form.Item
            label="收货人姓名"
            name="name"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="手机号码"
            normalize={(value) => formatPhone(value)}
            name="phone"
            rules={[{ required: true }]}
          >
            <Input addonBefore={'+86'} />
          </Form.Item>
          <Form.Item label="地址信息" name="city" rules={[{ required: true }]}>
            <Cascader
              options={options}
              //@ts-ignore
              loadData={loadData}
              placeholder={'请选择省/市/区'}
              changeOnSelect
            />
          </Form.Item>
          <Form.Item
            label="详细地址"
            name="address"
            rules={[{ required: true }]}
          >
            <Input.TextArea autoSize placeholder={'请输入详细地址信息'} />
          </Form.Item>
          <Form.Item valuePropName="checked" label="默认地址" name="is_default">
            <Checkbox
              disabled={defaultValue && Boolean(defaultValue.is_default)}
            >
              设为默认地址
            </Checkbox>
          </Form.Item>
          <Form.Item className={'text-center'}>
            <Button type={'primary'} htmlType={'submit'}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default memo(AddressFormModal);
